/**
 * Created by baiguiren on 2/14/17.
 */
let helper = require('../common/helper');
let _      = require('lodash');
let eventproxy = require('eventproxy');
let knex = require('../common/knex').knex;
let orderService = require('../services/orderService');
let async = require('async');
let wechatPayService = require('../services/WechatPayService');
let alipayService = require('../services/AlipayService');

exports = module.exports = {
  addOrder: function (req, res) {
    let merchant = req.session.user;
    if (!merchant) {
      return res.send(helper.apiFail('未登录'));
    }

    let ep = new eventproxy();

    let goods = _.trim(req._params.goods);
    let pay_type = req._params.pay_type || -1;
    let payer_phone = req._params.payer_phone;
    let merchant_address_id = req._params.merchant_address_id;
    if (helper.has_empty(goods, merchant_address_id) || pay_type == -1) {
      return res.send(helper.apiMissRequiredParams());
    }

    if (goods.toString().length == 0) {
      return res.send(helper.apiFail('请先添加商品'));
    }
    goods = goods.split(';');
    let goods_list = [], goods_arr, goods_ids = [], goods_id;
    for (let good of goods) {
      goods_arr = good.split(',');
      goods_id = goods_arr.shift();
      goods_ids.push(goods_id);
      goods_list.push({
        id: goods_id,
        amount: goods_arr.shift()
      });
    }

    let total_price, total_amount, order_goods_list;
    knex('tb_goods').whereIn('id', goods_ids).select('id', 'image', 'name', 'unit_price').then(function (result) {
      order_goods_list = result;
      let goods_id, goods_num;
      let order_goods = [];
      for (let goods of goods_list) {
        goods_id = goods.id;
        goods_num = goods.amount;
        for (let item of order_goods_list) {
          if (goods_id == item.id){
            //item.amount = goods_num
            total_price += goods_num * item.unit_price;
            total_amount += goods_num;
            order_goods.push({
              unit_price: item.unit_price,
              goods_id: goods_id,
              amount: goods_num,
              create_time: helper.time(),
              update_time: helper.time()
            });
          }
        }
      }
      ep.emit('order_goods', order_goods);
    });

    let payer_id = -1;
    ep.fail(function (message) {
      return res.send(helper.apiFail(message));
    });
    ep.all('get_address', 'payer_id', 'order_goods', 'history_payer', function (merchant_address, payer_id, order_goods, history_payer) {
      let order = {
        merchant_id: merchant.id,
        order_number: orderService.newOrderNum(),
        merchant_address_id: merchant_address_id,
        payer_id: payer_id,
        pay_type: pay_type,
        total_amount: total_amount,
        total_price: total_price,
        create_time: helper.time(),
        update_time: helper.time()
      };
      knex.transaction(function (trx) {
        knex('tb_order').insert(order).then(function (order_id) {
          if (!order_id) {
            trx.rollback();
            ep.emit('error', '新增订单失败');
          }

          ep.all('insert_payer', 'insert_order_goods', function (payer_id, order_goods) {
            trx.commit();
            knex('tb_order').where('id', order.id).first().then(function (order) {
              //todo 推送
              /**
               //申请代付推送
               if ($payer_id > 0) {
                $message = sprintf("%s向你发起了代付申请", $merchant['name']);
                //$pushService->payStatusChange($payer_id, 0, $message, $order_id);
                $this->dispatch(new PushJob($payer_id, 0, $message, $order_id));
               }
               */
              order.goods = order_goods_list;
              order.order_status = getOrderStatus(order, merchant);
              ep.all('order_goods_info', 'apply_payer_info', function (order_goods, apply_payer) {
                order.goods_name = order_goods;
                return res.send(helper.apiSuccess('提交订单成功', order));
              });
              getOrderGoodsInfo(order, ep);
              getApplyPayerInfo(order, merchant, ep);
            });
          });

          //添加历史代付人
          if (pay_type == 2 && !history_payer) {
            let merchant_payer = {
              merchant_id: merchant.id,
              payer_phone: payer_phone,
              create_time: helper.time(),
              update_time: helper.time()
            };
            knex('tb_merchant_payer').insert(merchant_payer).then(function (id) {
              if (!id) {
                trx.rollback();
                ep.emit('error', '添加代付人信息失败');
              } else {
                ep.emit('insert_payer', id);
              }
            });
          }

          for (let order_good of order_goods) {
            order_good.order_id = order_id;
          }

          //插入订单商品信息
          knex('tb_order_goods').insert(order_goods).then(function (result) {
            if (!result) {
              trx.rollback();
              ep.emit('error', '新增订单失败');
            } else {
              ep.emit('insert_order_goods', result);
            }
          });
        });
      });
    });

    knex('tb_merchant_address').where('id', merchant_address_id).where('is_deleted', 0).first().then(function (merchant_address) {
      if (!merchant_address) {
        ep.emit('error', '收货地址不存在');
      }
      if ([0, 1, 2].indexOf(parseInt(pay_type)) === -1) {
        ep.emit('error', '付款方式不存在');
      }
      ep.emit('get_address', merchant_address);
    });

    knex('tb_merchant').where({
      phone: payer_phone,
      is_deleted: 0,
      status: 1
    }).first().then(function (payer) {
      if (!payer && pay_type == 2) {
        ep.emit('error', '代付人不存在'); //找人代付的时候代付人不存在
      } else {
        ep.emit('payer_id', payer.id);
      }
    });

    //历史代付人信息表
    knex('tb_merchant_payer').where({
      payer_phone: payer_phone,
      merchant_id: merchant.id
    }).first().then(function (merchant_payer) {
      ep.emit('history_payer', merchant_payer);
    })
  },

  //取消订单、删除订单, 同时把order_goods的商品信息删除
  deleteOrder: function (req, res) {
    let merchant = req.session.user;
    if (!merchant) {
      return res.send(helper.apiFail('未登录'));
    }
    let order_id = req._params.order_id;
    if (!order_id) {
      return res.send(helper.apiMissRequiredParams());
    }
    knex.transaction(function (trx) {
      let ep = new eventproxy();
      ep.all('delete_order', 'delete_order_goods', function (affected_rows1, affected_rows2) {
        if (!affected_rows1 || !affected_rows2) {
          trx.rollback();
          return res.send(helper.apiFail('取消订单失败'));
        } else {
          trx.commit();
          return res.send(helper.apiSuccess('取消成功'));
        }
      });

      knex('tb_order').where('id', order_id).del().then(function (affected_rows) {
        ep.emit('delete_order', affected_rows);
      });
      knex('tb_order_goods').where('order_id', order_id).del().then(function (affected_rows) {
        ep.emit('delete_order_goods', affected_rows);
      });
    })
  },

  //拒绝代付api
  rejectPay: function (req, res) {
    let merchant = req.session.user;
    if (!merchant) {
      return res.send(helper.apiFail('未登录'));
    }
    let order_id = req._params.order_id;
    if (!order_id) {
      return res.send(helper.apiMissRequiredParams());
    }

    knex('tb_order').where({id: order_id, payer_id: merchant.id, is_deleted: 0}).first().then(function (order) {
      if (!order) {
        return res.send(helper.apiFail('订单不存在'));
      } else {
        //更新订单
        knex('tb_order').where('id', order_id).update({reject_pay: 1}).then(function (affected_rows) {
          if (affected_rows !== 1) {
            return res.send(helper.apiFail('拒绝代付失败'))
          } else {
            //todo 推送
            return res.send(helper.apiSuccess('已拒绝代付'));
          }
        });
      }
    })
  },

  updateOrder: function (req, res) {
    let merchant = req.session.user;
    if (!merchant) {
      return res.send(helper.apiNotLogin());
    }
    let order_id = req._params.order_id;
    let merchant_address_id = req._params.merchant_address_id;
    let pay_type = req._params.pay_type;
    let payer_phone = req._params.payer_phone;
    if (helper.has_empty(order_id, merchant_address_id, pay_type)) {
      return res.send(helper.apiMissRequiredParams());
    }

    let payer_id = -1;
    let ep = new eventproxy();
    ep.fail(function (message) {
      return res.send(helper.apiFail(message));
    });
    if (pay_type == 2) {
      knex('tb_merchant').where({
        phone: payer_phone,
        is_deleted: 0
      }).first().then(function (payer) {
        if (!payer) {
          ep.emit('error', '代付人不存在')
        }
        payer_id = payer.id;
        //在merchant_payer插入一条记录
        knex('tb_merchant_payer').insert({
          merchant_id: merchant.id,
          payer_phone: payer_phone,
          create_time: helper.time(),
          update_time: helper.time()
        }).then(function (id) {

        });
      })
    }
    knex('tb_order').where('id', order_id).update({
      merchant_address_id: merchant_address_id,
      pay_type: pay_type,
      payer_id: payer_id,
      update_time: helper.time()
    }).then(function (affected_rows) {
      if (affected_rows !== 1) {
        ep.emit('error', '更新订单失败');
      } else {
        return res.send(helper.apiSuccess('更新订单成功'));
      }
    })
  },

  //获取历史代付人手机号
  historyPayerPhone: function (req, res) {
    let merchant = req.session.user;
    if (!merchant) {
      return res.send(helper.apiNotLogin());
    }
    knex('tb_merchant_payer').where('merchant_id', merchant.id)
        .distinct('payer_phone').then(function (phones) {
      return res.send(helper.apiSuccess(phones));
    })
  },

  //获取订单列表, 包括其他人代付请求订单
  //付款:
  //     等待付款: 等待付款、等待代付、请求代付
  //     已付款: 已付款，已代付
  //     拒绝付款: 代付已被拒，代付已拒
  //发货:
  //     拣货中，已出库，已完成
  orderList: function (req, res) {
    //数据库状态 (0-等待付款, 1-等待发货, 2-拣货中,3-已出库,4-已完成)
    let merchant = req.session.user;
    if (!merchant) {
      return res.send(helper.apiNotLogin());
    }
    let type = req._params.type; //1-待付款, 2-待发货, 3-待收货, 4-已完成
    let server_time = req._params.server_time || helper.time();
    if (!type) {
      return res.send(helper.apiMissRequiredParams());
    }
    let builder = knex('tb_order').where('is_deleted', 0).where(function () {
      this.where('merchant_id', merchant.id).orWhere('payer_id', merchant.id);
    });
    //1-待付款, 2-待发货, 3-待收货, 4-已完成
    if (type == 4) {
      builder.where(function () {
        //自己付款的订单
        this.where('status', 4).where('merchant_id', merchant.id);
      }).orWhere(function () {
        //已代付的订单
        this.where('pay_status', 1).where('payer_id', merchant.id);
      });
    } else if (type == 3) {
      //待收货, 属于自己的订单
      builder.where(function () {
        let that = this; //todo test
        this.where('merchant_id', merchant.id)
            .where(function () {
              that.where('status', 2).orWhere('status', 3);
            });
      });
    } else if (type == 2) {
      //已付款
      builder.where('pay_status', 1).where('status', 1).where('merchant_id', merchant.id);
    } else if (type == 1) {
      //待付款
      builder.where('pay_status', 0);
    } else {
      return res.send(helper.apiFail('参数错误'));
    }

    let current_page = req._params.page || 1;
    let ep = new eventproxy();
    builder.where('create_time', '<', server_time).orderBy('update_time', 'desc').orderBy('id', 'desc')
        .paginate(null, current_page).then(function (list) {
      ep.all('process_goods_info', 'process_payer_info', function () {
        return res.send(helper.apiSuccess(list));
      });
      ep.after('order_goods_info', list.length, function (order_goods_info_list) {
        async.each(order_goods_info_list, function (data, callback) {
          callback(null);
        }, function (err) {
          ep.emit('process_goods_info');
        })
      });
      ep.after('apply_payer_info', list.length, function (payer_info_list) {
        async.each(payer_info_list, function (data, callback) {
          callback(null);
        }, function (err) {
          ep.emit('process_payer_info');
        })
      });
      for (let order of list) {
        getOrderGoodsInfo(order, ep);
        getApplyPayerInfo(order, merchant, ep);
        order.order_status = getOrderStatus(order, merchant, type);
        if (order.payer_id > 0 && order.pay_status == 0) {
          //他人代付订单
          order.pay_type = 2;
        }
      }
    })
  },

  //获取订单详情, 包括所有商品列表
  orderInfo: function (req, res) {
    let merchant = req.session.user;
    if (!merchant) {
      return res.send(helper.apiNotLogin());
    }
    let order_id = req._params.order_id;
    if (!order_id) {
      return res.send(helper.apiMissRequiredParams());
    }

    let ep = new eventproxy();
    knex('tb_order').where('id', order_id).first().then(function (order) {
      if (!order) {
        return res.send(helper.apiFail('订单不存在'));
      }
      knex('tb_order_goods').where('order_id', order_id).pluck('goods_id').then(function (order_goods) {
        let goods_ids = order_goods.map(function (order_good) {
          return order_good.goods_id;
        });
        ep.all('apply_payer_info', 'order_goods_info', 'get_goods', function (payer_info, goods_info, goods) {
          order.goods = goods;
          return res.send(helper.apiSuccess(order));
        });
        getApplyPayerInfo(order, merchant, ep);
        getOrderGoodsInfo(order, ep);
        order.order_status = getOrderStatus(order, merchant, 0, order.status);
        if (order.payer_id > 0 && order.pay_status == 0) {
          //他人代付订单
          order.pay_type = 2;
        }
        knex('tb_order_goods').join('goods', 'goods.id', '=', 'order_goods.goods_id')
            .where('order_goods.order_id', '=', order_id)
            .whereIn('goods.id', goods_ids)
            .select('goods.id', 'goods.image', 'goods.name', 'goods.unit_price', 'amount')
            .then(function (goods) {
              ep.emit('get_goods', goods);
            });
      })
    })
  },

  //获取商品最新信息
  goodsInfo: function (req, res) {
    let goods_id = _.trim(req._params.goods_id);
    if (!goods_id) {
      return res.send(helper.apiMissRequiredParams());
    }
    let goods_ids_array = goods_id.split(',').map(parseInt);
    let exist_goods_id, not_exist_goods_id, not_exist_goods=[];
    knex('tb_view_goods').whereIn('id', goods_ids_array)
        .orderByRaw('field(id, ' + goods_id + ')')
        .select('*', 'status as is_exist')
        .then(function (goods) {
          exist_goods_id = goods.map(item=>{return item.id;});
          not_exist_goods_id = _.difference(goods_ids_array, exist_goods_id);
          _.forEach(not_exist_goods_id, function (id) {
            not_exist_goods.push({
              id: id,
              is_exist: 0
            });
          });
          goods = goods.concat(not_exist_goods);
          //todo 替换图片url
          /**
           foreach ($goods as &$value) {
            if ($value['is_exist']) {
                $value['image'] = wrap_image_url($value['image'], ['width' => 160, 'height' => 160]);
            }
           }
           */
          return res.send(helper.apiSuccess(goods));
        });
  },

  //获取上次提交订单的地址
  lastAddress: function (req, res) {
    let merchant = req.session.user;
    if (!merchant) {
      return res.send(helper.apiNotLogin());
    }
    knex('tb_order').where('merchant_id', merchant.id).orderBy('create_time', 'desc')
        .where('is_deleted', 0).first().then(function (order) {
      if (!order) {
        //还没下过订单
        return res.send(helper.apiSuccess());
      } else {
        knex('tb_merchant_address').where({
          is_deleted: 0,
          id: order.merchant_address_id
        }).first().then(function (merchant_address) {
          return res.send(helper.apiSuccess(merchant_address));
        })
      }
    })
  },

  //统一支付接口
  //todo payservice
  payOrder: function (req, res) {
    let merchant = req._params.user;
    if (!merchant) {
      return res.send(helper.apiNotLogin());
    }
    let type = req._params.type;
    let order_id = req._params.order_id;
    if (type === undefined) {
      return res.send(helper.apiMissRequiredParams());
    }
    type = parseInt(type);
    if ([0, 1].indexOf(type) === -1) {
      return res.send(helper.apiFail('支付方式不存在'));
    }
    let ep = new eventproxy();
    knex('tb_order').where('id', order_id).first().then(function (order) {
      if (!order) {
        return res.send(helper.apiFail('订单不存在'));
      }
      if (order.pay_status == 1) {
        return res.send(helper.apiFail('订单已支付, 请勿重复提交'));
      }
      order.order_status = getOrderStatus(order, merchant, 0, order.status);
      ep.on('order_goods_info', function (goods_info) {
        if (type == 0) {
          //todo makeOrder
          order.alipay_data = alipayService.makeOrder(order.order_number, '商品名称', '商品详情', '0.01');
        }
        if (type == 1) {
          //微信支付
          order.wechat_data = {};
          //todo makeOrder
          let result = wechatPayService.makeOrder(order.id, order.order_number, '贝壳速配-商品购买', order.total_price);
          if (helper.strcmp(result.return_code, 'SUCCESS') !== 0) {
            return res.send(helper.apiFail('支付失败'));
          }
          result.wechat_data.timeStamp = helper.time();
          order.wechat_data = result.wechat_data;
        }
        return res.send(helper.apiSuccess(order));
      });
      getOrderGoodsInfo(order);
    });
  }
};

//根据订单表信息获取订单状态
let getOrderStatus = function (order, merchant, type=0, current_status=0) {
  /*
   $status =[  1=>"等待付款", 2=>"已付款",
   3=>"请求代付", 4=>"等待代付", 5=>"已代付",
   6=>"代付已被拒", 7=>"代付已拒",
   8=>"拣货中", 9=>"已出货", 10=>"已完成",
   11=>  别人代付成功
   ];
   */
  let status;
  //数据库状态 (0-等待付款, 1-等待发货, 2-拣货中,3-已出库,4-已完成)
  if (type == 0) {
    if (current_status == 4) {
      type = 4;
    } else if (current_status == 2 || current_status == 3) {
      type = 3;
    } else if (current_status == 1) {
      type = 2;
    } else {
      type = 1;
    }
  }

  //$type 1-待付款, 2-待发货, 3-待收货, 4-已完成
  if (type == 4) {
    //支付状态是已完成
    if (order.payer_id == merchant.id) {
      status = 5;
    } else {
      status = 10;
    }
  } else if (type == 3) {
    if (order.status == 2) {
      status = 8;
    } else if (order.status == 3) {
      status = 9;
    }
  } else if (type == 2) {
    //已付款的, 待发货
    if (order.merchant_id == merchant.id) {
      //自己的订单
      status = 2; //自己支付
      if (order.payer_id > 0) {
        //别人代付
        status = 11;
      }
    } else if (order.payer_id == merchant.id) {
      //帮别人代付
      status = 5;
    }
  } else if (type == 1) {
    if (order.payer_id < 0) {
      //等待自己付款
      status = 1;
    } else if (order.payer_id == merchant.id) {
      //等待帮忙代付
      if (order.reject_pay == 1) {
        //代付已拒
        status = 7;
      } else {
        //等待代付
        status = 3;
      }
    } else {
      //等待别人代付
      if (order.reject_pay == 1){
        //别人拒绝代付
        status = 6;
      } else {
        //等待别人代付
        status = 4;
      }
    }
  }

  return status;
};

let getOrderGoodsInfo = function (order, ep) {
  //获取订单的商品信息
  knex('tb_order_goods').where('order_id', order.id).pluck('goods_id').first().then(function (result) {
    knex('tb_goods').where('id', result.goods_id).pluck('name').first().then(function (result) {
      order.name = result.name;
      ep.emit('order_goods_info', result.name);
    });
  })
};

//获取代付人姓名或者申请代付人姓名
let getApplyPayerInfo = function (order, merchant, ep) {
  //别人申请代付的订单, 返回申请人名称
  if (order.payer_id == merchant.id) {
    knex('tb_merchant').where('id', order.merchant_id).first('name').then(function (result) {
      order.apply_payer_name = result.name;
      ep.emit('apply_payer_info', result.name);
    });
  }
  //别人帮忙代付的订单, 返回代付人名称
  if (order.merchant_id == merchant.id && order.payer_id > 0) {
    knex('tb_merchant').where('id', order.payer_id).first('name').then(function (result) {
      order.payer_name = result.name;
      ep.emit('apply_payer_info', result.name);
    })
  }
};